來架個網站吧 Grails今天讓我們回到第14天一開始建立的 Controller 。
Grails Controller 是一般API會直接觸及的程式,在這邊主要是處理業務流程。Controller 中有兩項比較常被用到: render、redirect。
render 是表明要回傳的資料。資料可以是TEXT、JSON、view、templates等形式。在程式中的寫會是如下:
class ExampleController {
    def dictService
    def index(){
      render(view: "example")
    }
    /**
     * 查詢
     * @return
     */
    JSON filter(){
        LinkedHashMap result = dictService.filter(params)
        render result as JSON
    }
}
redirect 顧名思義是跳轉的概念。會在 Web Server 中使用 HTTP 通訊協定重新導向到新增目的地。在程式中的寫會是如下:
class ExampleController {
    def index(){
      redirect controller: 'dict', action: 'index' ,id: 'test'
    }
    def goToGoogle(){
        redirect(url: "http://www.google.com")
    }
}
在這邊有草過一個坑: 在 redirect 中參數 id 傳遞中文需要進行 URL encode,不然出現下列類似錯誤
tomcat The Unicode character [主] at code point [20,027] cannot be encoded as it is outside the permitted range of 0 to 255。
出現這個問題,主要是在RFP822 3.1.2章節中 HTTP 表頭規範需要在 0到 255 的ASCII代碼範圍中,且不包含小數點及冒號。
今天的程式進度如下:
package dict
import grails.converters.JSON
class DictController {
    def dictService
    def index() { }
    /**
     * 查詢
     * @return
     */
    JSON filter(){
        LinkedHashMap result = dictService.filter(params)
        render result as JSON
    }
}
RFP822 3.1.2: STRUCTURE OF HEADER FIELDS